package top.someapp.dxf2dsvg.dxf;

import top.someapp.dxf2dsvg.base.DxfException;

import javax.annotation.Nonnull;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.io.LineNumberReader;
import java.util.regex.Pattern;

/**
 * dxf file reader.
 *
 * @author zwz
 * Created on 2020-04-17
 */
public class DxfReader {
    private static final Pattern codeZeroReg = Pattern.compile("\\s+0");
    private final File dxfFile;
    private final LineNumberReader reader;
    private boolean start;
    private boolean finished;

    public DxfReader(@Nonnull File dxfFile) throws IOException {
        this.dxfFile = dxfFile;
        reader = new LineNumberReader(new FileReader(dxfFile));
    }

    public File getDxfFile() {
        return dxfFile;
    }

    private String nextLine() {
        String line = null;
        try {
            line = reader.readLine();
        } catch (IOException e) {
            e.printStackTrace();
            finished = true;
        }
        if (!start) {
            start = codeZeroReg.matcher(line).matches();
        }
        if ("EOF".equals(line)) {
            finished = true;
        }
        return line;
    }

    Item next() {
        if (finished) return null;
        String code;
        String value;
        if (start) {
            code = nextLine();
            value = nextLine();
        } else {
            for (; ; ) {
                code = nextLine();
                if (start) {
                    value = nextLine();
                    break;
                }
            }
        }
        return value == null ? null : new Item(code, value);
    }

    void readToDxf(@Nonnull Dxf dxf) {
        for (; ; ) {
            Item item = next();
            if (item == null)
                return;

            if (item.value.equals("SECTION")) {
                item = next();
                Section section;
                try {
                    section = Sections.parse(this, item);
                } catch (Exception e) {
                    e.printStackTrace();
                    throw new DxfException(getDxfFile().getName() + " line: " + reader.getLineNumber() +
                            "\t" + e.getMessage());
                }
                if (section != null) {
                    System.out.println("============== <" + section.name() + "> =================");
                    System.out.println(section);
                    dxf.onSectionFound(section);
                    System.out.println("============== </" + section.name() + "> =================");
                }
            }
        }
    }
}
